﻿using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;

public class MySqlDataStorer : DataStorer
{
    public MySqlDataStorer(string connectionString) : base(connectionString) { }

    public override async Task<int> StoreDevicesAsync(List<Device> devices)
    {
        int count = 0;
        foreach (var device in devices)
        {
            var sql = @"
                INSERT INTO devices 
                (device_addr, device_name, group_id, lat, lng, last_update)
                VALUES (@deviceAddr, @deviceName, @groupId, @lat, @lng, @now)
                ON DUPLICATE KEY UPDATE
                device_name = VALUES(device_name),
                lat = VALUES(lat),
                lng = VALUES(lng),
                last_update = VALUES(last_update)";
            using var cmd = new MySqlCommand(sql, _dbConnection);
            cmd.Parameters.AddWithValue("@deviceAddr", device.DeviceAddr);
            cmd.Parameters.AddWithValue("@deviceName", device.DeviceName);
            cmd.Parameters.AddWithValue("@groupId", device.GroupId);
            cmd.Parameters.AddWithValue("@lat", device.Lat ?? 0);
            cmd.Parameters.AddWithValue("@lng", device.Lng ?? 0);
            cmd.Parameters.AddWithValue("@now", System.DateTime.Now);
            count += await cmd.ExecuteNonQueryAsync();
        }
        return count;
    }

    public override async Task<int> StoreRealtimeDataAsync(List<RealtimeData> realtimeData)
    {
        int count = 0;
        foreach (var deviceData in realtimeData)
        {
            foreach (var dataItem in deviceData.DataItem)
            {
                foreach (var regItem in dataItem.RegisterItem)
                {
                    var sql = @"
                        INSERT INTO realtime_data 
                        (device_addr, factor_id, value, unit, alarm_level, timestamp, fetch_time)
                        VALUES (@addr, @factorId, @value, @unit, @alarmLevel, @ts, @fetchTime)";
                    using var cmd = new MySqlCommand(sql, _dbConnection);
                    cmd.Parameters.AddWithValue("@addr", deviceData.DeviceAddr);
                    cmd.Parameters.AddWithValue("@factorId", $"{dataItem.NodeId}_{regItem.RegisterId}");
                    cmd.Parameters.AddWithValue("@value", regItem.Value);
                    cmd.Parameters.AddWithValue("@unit", regItem.Unit);
                    cmd.Parameters.AddWithValue("@alarmLevel", regItem.AlarmLevel);
                    cmd.Parameters.AddWithValue("@ts", deviceData.TimeStamp);
                    cmd.Parameters.AddWithValue("@fetchTime", System.DateTime.Now);
                    count += await cmd.ExecuteNonQueryAsync();
                }
            }
        }
        return count;
    }
}